﻿using System;
using System.Collections.Generic;
using System.Web;


namespace CCPSIP.Robot
{
    /// <summary>CCPSIP_040：機器人取得 User 資訊 API</summary>
    /// SERVICE_ID = 機器人服務ID。
    /// Password = 機器人服務密碼。
    /// SIP_Num = User 的 SIP 帳號。
    /// MobileNum = User 的手機門號（含國碼）。
    /// （SIP_Num / MobileNum 至少須傳其中一個）

    public class get_user_info : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";


            try
            {
                //【01】檢查呼叫端的 IP Address 是否合法
                //
                string ipAddr = ChrisKit.getIPAddress(req);
                if (!RobotKit.isAllowRobotIP(ipAddr))
                {
                    throw new Exception("ERROR_01: Access Denied");//拒絕存取
                }


                //【02】取得POST參數，驗證身分
                //
                string SERVICE_ID = req.Form["SERVICE_ID"];//機器人服務ID
                string Password = req.Form["Password"];    //機器人服務密碼
                string SIP_Num = req.Form["SIP_Num"];    //User SIP帳號
                string MobileNum = req.Form["MobileNum"];//User 手機門號(含國碼)

                RobotServiceInfo serviceInfo = RobotKit.getServiceInfo(SERVICE_ID, Password);
                if (serviceInfo == null)
                {
                    throw new Exception("ERROR_02: Service Authentication Failed");//服務認證失敗
                }


                //【03】檢查UserID
                //
                if (string.IsNullOrEmpty(SIP_Num))
                {
                    string[] UserIDs = OracleKitUser.getUserIDbyMobile(MobileNum);

                    if (UserIDs != null && UserIDs.Length > 0)
                        SIP_Num = UserIDs[0];
                }

                if (!OracleKitUser.hasUser(SIP_Num))
                {
                    throw new Exception("ERROR_03: User not found");//找不到User
                }


                //【04】取得 User 資訊
                //
                Dictionary<string, string> userDict = new Dictionary<string, string>();
                userDict["SIP_Num"] = SIP_Num;
                userDict["CustomName"] = SipKit.getCustomName(SIP_Num);


                //【99】回傳結果
                //
                resp.ContentType = "application/json";
                resp.Charset = null;
                fastJSON.JSON.Instance.Parameters.EnableAnonymousTypes = true;
                resultStr = fastJSON.JSON.Instance.ToJSON(userDict);
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
